# -*- coding: utf-8 -*-
import asyncio
import os
import botpy
from botpy import logging
from botpy.ext.cog_yaml import read
from botpy.message import GroupMessage, Message, C2CMessage
from message_recognition import process_message_content
import shutil
import datetime
from database_basic import game_update, create_database, game_day_update
from database_equipments import create_equipments
from database_evolution import create_evolution
from database_maps import create_maps
from database_monsters import create_monsters
from database_shops import create_shops
from database_skills import create_skills


test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml"))

_log = logging.get_logger()


class MyClient(botpy.Client):
    async def on_ready(self):
        _log.info(f"robot 「{self.robot.name}」 on_ready!")
        # 启动定时任务
        if not os.path.exists("data备份"):
            os.makedirs("data备份")
        await create_database()
        await create_equipments()
        await create_evolution()
        await create_maps()
        await create_monsters()
        await create_skills()
        now = datetime.datetime.now() + datetime.timedelta(hours=0)
        current_time = now.strftime("%Y-%m-%d %H:%M:%S")
        current_folder = os.path.dirname(os.path.abspath(__file__))
        source_folder = current_folder + "/data"
        destination_folder = current_folder + "/data备份/"
        shutil.copytree(source_folder, destination_folder + current_time)
        loop = asyncio.get_event_loop()
        loop.create_task(copy_folder_on_hourly_basis(source_folder, destination_folder))

    async def on_group_at_message_create(self, message: GroupMessage):

        await process_message_content(message)

    async def on_c2c_message_create(self, message: C2CMessage):

        await process_message_content(message)

async def copy_folder_on_hourly_basis(source_folder, destination_folder):
    while True:
        # 获取当前时间
        now = datetime.datetime.now() + datetime.timedelta(hours=0)
        current_time = now.strftime("%Y-%m-%d %H:%M:%S")
        # 如果当前时间是整点
        if now.minute == 0 and now.second == 0:
            # 复制文件夹
            shutil.copytree(source_folder, destination_folder + current_time)
            await game_update()
        if now.hour == 0 and now.minute == 0 and now.second == 0:
            await game_day_update()
        # 等待1秒钟
        await asyncio.sleep(1)


if __name__ == "__main__":
    # 通过预设置的类型，设置需要监听的事件通道
    # intents = botpy.Intents.none()
    # intents.public_messages=Tru

    # 通过kwargs，设置需要监听的事件通道
    intents = botpy.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])